package com.lwh.easyExcel.controller;



import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.lwh.common.util.DateUtil;
import com.lwh.easyExcel.entity.BdCheliangEntity;
import com.lwh.easyExcel.service.BdCheliangService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Callable;


/**
 * @Title: Controller
 * @Description: 车辆管理
 * @author
 * @date
 * @version
 *
 */
@Controller
@RequestMapping("/bdCheliang")
public class BdCheliangController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BdCheliangController.class);

	@Autowired
	private BdCheliangService bdCheliangService;

	@Autowired
	private Validator validator;

	// 查询页面内容
	@RequestMapping("/findPage")
	@ResponseBody
	public Callable<Map<String, Object>> findPage(BdCheliangEntity query) {

		if (query.getPage() == null) {
			query.setPage(1);
		}
		if (query.getRows() == null) {
			query.setRows(10);
		}
		Callable<Map<String, Object>> callable = (() -> bdCheliangService.findPage(query));
		return callable;
	}

	/**
	 * 增加功能
	 *
	 * @param
	 * @return
	 */
	@PostMapping("/addCheliang")
	@ResponseBody
	public Callable<String> add(BdCheliangEntity bdCheliangEntity) {

		Callable<String> callable = null;

		try {
			bdCheliangService.insertSelective(bdCheliangEntity);
			callable = () -> {
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统出错了";
			};
		}
		return callable;
	}

	// 修改
	@PostMapping("/updateCheliang")
	@ResponseBody
	public Callable<String> update(BdCheliangEntity adCheliangEntity) {

		Callable<String> callable = null;
		if (adCheliangEntity.getId() == null) {
			callable = () -> {
				return "系统缺少参数";
			};
			return callable;
		}
		try {
			callable = () -> {
				bdCheliangService.updateByPrimaryKeySelective(adCheliangEntity);
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统发生错误";
			};
		}
		return callable;
	}


	// 批量删除
	@RequestMapping("/deleteCheliang")
	@ResponseBody
	public Callable<String> delete(String[] ids) {
		Callable<String> callable = null;
		if (ids == null || ids.length == 0) {
			callable = () -> {
				return "系统缺少参数";
			};
			return callable;
		}
		try {
			callable = () -> {
				bdCheliangService.deleteByIds(ids);
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统发生错误";
			};
		}
		return callable;
	}

	// 单独删除
	@RequestMapping("/deleteOneCheliang")
	@ResponseBody
	public Callable<String> deleteOne(String id) {
		Callable<String> callable = null;
		if (id == null) {
			callable = () -> {
				return "系统缺少参数";
			};
			return callable;
		}
		try {
			callable = () -> {
				bdCheliangService.deleteOneById(id);
				return "删除成功";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = () -> {
				return "系统发生错误";
			};
		}
		return callable;
	}

	// 导入
	@RequestMapping("/importExcel")
	@ResponseBody
	public String importExcel(MultipartFile uploadFile) {
		String result = null;
		InputStream is = null;
		try {
			String filename = uploadFile.getOriginalFilename();
			if (filename != null && (filename.toLowerCase().endsWith(".xls") || filename.toLowerCase().endsWith(".xlsx"))) {
				is = new BufferedInputStream(uploadFile.getInputStream());
			} else {
				return "导入的文件不是excel文件";
			}
			result = bdCheliangService.readExcel(is);
		} catch (Exception e) {
			e.printStackTrace();
			return "系统发生错误";
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;

	}

	/*// 导出
	@RequestMapping("/exportExcel")
	@ResponseBody
	public Map<String, Object> outExcel(BdCheliangEntity bdCheliangEntity) {

		return bdCheliangService.outExcel(bdCheliangEntity);
	}*/

	// 导出
	@ResponseBody
	@RequestMapping("/exportExcel")
	public String exporExcel(BdCheliangEntity bdCheliangEntity, HttpServletResponse response) throws IOException {
		String result = null;
		ExcelWriter writer = null;
		OutputStream outputStream = response.getOutputStream();
		try {
			String fileName ="车辆信息.xls";
			//添加响应头信息
			response.setHeader("Content-disposition", "attachment; filename=" +  URLEncoder.encode(fileName,"UTF-8"));
			response.setContentType("application/msexcel;charset=UTF-8");//设置类型
			response.setHeader("Pragma", "No-cache");//设置头
			response.setHeader("Cache-Control", "no-cache");//设置头
			response.setDateHeader("Expires", 0);//设置日期头

			// 实例化 ExcelWriter，两种方法,一种是EasyExcelFactory.getWriter方法，一种是ExcelWriter方法
			// 这种一般导出的是xlsx格式的excel文件
			// writer = EasyExcelFactory.getWriter(outputStream);
			// 这种可以自定义导出excel的格式
			writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);

			// 实例化表单
			// Sheet(参数一，参数二，参数三)：
			// 参数一为读取哪一个表单，例如1代表第一个工作表
			// 参数二为从哪一行开始读取( 不包括定义的这一行，比如 headLineMun为2 ，那么取出来的数据是从 第三行的数据开始读取 )
			// 参数三为要导出的实体类的class文件
			Sheet sheet = new Sheet(1, 0, BdCheliangEntity.class);

			// 设置工作表名
			sheet.setSheetName("车辆信息");

			// 获取list数据
			List<BdCheliangEntity> list = bdCheliangService.outExcel(bdCheliangEntity);

			// 输出
			// list为数据源，sheet为表单
			writer.write(list, sheet);
			writer.finish();

			outputStream.flush();
			outputStream.close();
			result = "success";
		} catch (IOException e) {
			e.printStackTrace();
			result = "fail";
		} finally {
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return result;
	}


	// 模板下载
	@RequestMapping("/modelExcel")
	@ResponseBody
	public void modelExcel(HttpServletResponse response) {

		List<BdCheliangEntity> list = new ArrayList<>();
		try {
			createExcelStreamMutilByEaysExcel(response, list, ExcelTypeEnum.XLS, "车辆信息.xls");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @Author
	 * @Description 导出excel 支持一张表导出多个sheet
	 * @Param OutputStream 输出流
	 * Map<String, List>  sheetName和每个sheet的数据
	 * ExcelTypeEnum 要导出的excel的类型 有ExcelTypeEnum.xls 和有ExcelTypeEnum.xlsx
	 */
	public static void createExcelStreamMutilByEaysExcel(HttpServletResponse response, List<BdCheliangEntity> list, ExcelTypeEnum type, String fileName) throws UnsupportedEncodingException {
		try {
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
			ServletOutputStream out = response.getOutputStream();

			ExcelWriter writer = new ExcelWriter(out, type, true);
			Sheet sheet = new Sheet(1, 0,BdCheliangEntity.class);
			sheet.setSheetName("车辆管理");
			writer.write(list, sheet);
			writer.finish();
			out.flush();
			System.out.println("导出完成");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	}





